package com.ruoyi.mongo.souce;

import java.util.Arrays;
import org.bson.Document;
// import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;

/**
 * @Description: 创建MongoDB链接-使用用户认证
 * @ClassName: MongoDB03AuthUtil
 * @author syc
 * @date: 2022年5月25日 上午10:42:33
 */
@SuppressWarnings("deprecation")
public class MongoDB03AuthUtil {
//    private static MongoClient client = null;
//    static{
//        if(client == null) {        	
//            // 创建一个封装用户认证信息
//            MongoCredential credential = MongoCredential.createCredential("root","admin","sykj85575700".toCharArray());
//            // 封装MongoDB的地址与端口
//            ServerAddress address = new ServerAddress("192.168.1.125",27017);
//            client = new MongoClient(address, Arrays.asList(credential));
//        }
//    }

    // 获取MongoDB数据库
    public static MongoDatabase getDatabase(String dbName) {
        // return client.getDatabase(dbName);
        return null;
    }

    // 获取MongiDb中的集合
    public static MongoCollection<Document> getCollection(String dbName , String collName) {
        MongoDatabase database = getDatabase(dbName);
        return database.getCollection(collName);
    }
    
    /**
     * @Description:测试 
     * @author syc
     * @date: 2022年5月25日 上午10:27:05
     */
    public static void main(String[] args) {

    	MongoCollection<Document>	collection = MongoDB03AuthUtil.getCollection("test", "test_user");
    	 FindIterable<Document> iterable = collection.find();
         MongoCursor<Document> cursor = iterable.iterator();
         while(cursor.hasNext()){
            // 每掉一次next移动以下指针
            Document docu = cursor.next();
            System.out.println(docu.get("name")+"\t" + docu.get("age") + "\t" + docu.get("sex") + "\t" + docu.get("secrets"));
         }
	}
    
}
